<?php
namespace app\admin\controller;

class ChargeOrder extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function orderList() {
        if($this->noLogin()){
            return $this->noLoginReturn();
        }

        $role = $this->role;
        $userId = $this->userid;
        
        $params = request()->get();
        $page = isset($params['page']) ? intval($params['page']) : 1;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 20;
        $offset = ($page - 1) * $pageSize;
        $type = isset($params['type']) ? intval($params['type']) : 1; //1：扫码充电，2：线上卡充电
        
        $time = time();
        $where = [];
        
        $orderNo = isset($params['orderNo']) ? trim($params['orderNo']) : '';
        
        if($orderNo !== '') { //如果有订单号，忽略其他条件
            $where[] = ['order_no', '=', $orderNo];
        }else{
            if($type === 2) {
                $cardNo = isset($params['cardNo']) ? trim($params['cardNo']) : '';
                if($cardNo !== '') {
                    $where[] = ['card_no', '=', $cardNo];
                }
            }
            
            
            $deviceNo = isset($params['deviceNo']) ? trim($params['deviceNo']) : '';
            if($deviceNo !== '') {
                $where[] = ['order_no', '=', $deviceNo];
            }
            
            $status = isset($params['status']) ? intval($params['status']) : 0;
            if($status !== 0) {
                $where[] = ['status', '=', $status];
            }else {
                $where[] = ['status', 'in', [1, 2]];
            }
            
            $startTime = isset($params['start']) ? trim($params['start']) : '';
            $endTime = isset($params['end']) ? trim($params['end']) : '';
            if($startTime === $endTime && $startTime !== '') { //查询当日
                $startTime = strtotime($startTime);
                $endTime = strtotime('+ 1 day', $startTime);
                $where[] = ['start_time', '>=', $startTime];
                $where[] = ['end_time', '<', $endTime];
            }else{
                if($startTime !== '') {
                    $startTime = strtotime($startTime);
                    $where[] = ['start_time', '>=', $startTime];
                }
                
                if($endTime !== '') {
                    $endTime = strtotime($endTime);
                    $where[] = ['start_time', '<', $endTime];
                }
                
            }
        }
        
        $excludeField = ['user_id', 'avg_power', 'max_power'];
        switch ($type) {
            case 1 : 
                array_push($excludeField, 'form_id', 'pay_status');
                $orderModel = model('ChargeOrder');
                break;
            case 2 : 
                $orderModel = model('CardChargeOrder');
                break;
        }
        
        if($role == 1) { //平台
            $agentId = isset($params['agentId']) ? intval($params['agentId']) : 0;
            if($agentId > 0) {
                $where[] = ['agent_id', '=', $agentId];
            }
            
        }elseif($role == 2) {
            $where[] = ['agent_id', '=', $userId];
            array_push($excludeField, 'agent_id');
        }else{
            $where[] = ['store_id', '=', $userId];
            array_push($excludeField, 'agent_id', 'store_id');
        }
        
        $repData = ['list' => []];
        
        $orderList = $orderModel->where($where)->order('order_id desc')->limit($offset, $pageSize)->select()->toArray();
        if(empty($orderList)) {
            return successResult($repData);
        }
        
        if($role == 1) { //平台
            $agentIds = [];
            $storeIds = [];
            foreach ($orderList as $order) {
                if($order['agent_id'] > 0) {
                    if(!in_array($order['agent_id'], $agentIds)) {
                        array_push($agentIds, $order['agent_id']);
                    }
                    
                    if($order['store_id'] > 0 && !in_array($order['store_id'], $storeIds)) {
                        array_push($storeIds, $order['store_id']);
                    }
                }
            }
            
            $agentList = [];
            $storeList = [];
            
            if(!empty($agentIds)) {
                $agentList = model('Agent')->findAll(['agent_id' => $agentIds], ['agent_id', 'agent_name']);
                
                if(!empty($storeIds)){
                    $storeList = model('Store')->findAll(['store_id' => $storeIds], ['store_id', 'store_name']);
                }
                
                foreach ($orderList as &$order) {
                    if($order['agent_id'] > 0) {
                        foreach ($agentList as $agent) {
                            if($order['agent_id'] == $agent['agent_id']) {
                                $order['agent_name'] = $agent['agent_name'];
                                break;
                            }
                        }
                        if($order['store_id'] > 0) {
                            foreach ($storeList as $store) {
                                if($order['store_id'] == $store['store_id']) {
                                    $order['store_name'] = $store['store_name'];
                                    break;
                                }
                            }
                        }
                    }
                    
                    
                }
            }
            
        }elseif($role == 2) { //代理商
            $storeIds = [];
            foreach ($orderList as $order) {
                if($order['store_id'] > 0 && !in_array($order['store_id'], $storeIds)){
                    array_push($storeIds, $order['store_id']);
                }
            }
            
            if(!empty($storeIds)) {
                $storeList = model('Store')->findAll(['store_id' => $storeIds], ['store_id', 'store_name']);
                foreach ($orderList as &$order) {
                    if($order['store_id'] > 0) {
                        foreach ($storeList as $store) {
                            if($order['store_id'] == $store['store_id']) {
                                $order['store_name'] = $store['store_name'];
                                break;
                            }
                        }
                    }
                    
                }
            }
            
        }else{ //门店
            
        }
        
        $repData['list'] = $orderList;
        
        if(isset($params['init']) && $params['init'] == 1){
            $repData['total'] = $orderModel->where($where)->count();
        }
        
        return successResult($repData);
        
    }
    
    public function orderDetail() {
        $orderId = request()->get('orderId', 0, 'intval');
        if($orderId <= 0) {
            return errorResult();
        }
        
        $role = $this->role;
        $userId = $this->userid;
        
        $order = model('ChargeOrder')->findOne(['order_id' => $orderId]);
        
        if(empty($order) || ($role == 2 && $order['agent_id'] != $userId) || ($role == 3 && $order['store_id'] != $userId)) {
            return errorResult();
        }
        
        if($order['agent_id'] > 0) {
            $order['agent_name'] = model('Agent')->where(['agent_id' => $order['agent_id']])->value('agent_name');
            
            if($order['store_id'] > 0) {
                $order['store_name'] = model('Store')->where(['store_id' => $order['store_id']])->value('store_name');
            }
        }
        
        
        if($order['status'] == 1) { //充电中
            $port = model('DevicePort')->findOne(['device_id' => $order['device_id'], 'port_no' => $order['port_no']], ['surplus_time', 'surplus_energy', 'power']);
            list($order['surplus_time'], $order['surplus_energy'], $order['power']) = array_values($port);
        }else if($order['status'] == 2) {
            if($order['agent_id'] > 0) {
                $order['store_profit'] = roundNumber($order['consume_amount'] * $order['profit_rate'] / 100, 2);
                $order['agent_profit'] = $order['consume_amount'] - $order['store_profit'];
            }
        }
        
        $extendOrder = model('ExtendChargeOrder')->findAll(['charge_order_id' => $orderId, 'status' => 1], ['order_no', 'extend_quantity', 'amount', 'create_time']);
        
        return successResult(['order' => $order, 'extendOrder' => $extendOrder]);
        
    }
}














